import 'dart:io';

import 'package:dy_download_utils/bean_download_result.dart';
import 'package:dy_download_utils/controller_dy.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class InfoPage extends StatelessWidget {
  final int index;
  final DownloadInfo info;

  const InfoPage(this.index, this.info, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Widget> children = [];
    children.add(SizedBox(height: 20.0));
    children.add(Container(
      child: Text(
        info.desc!,
        style: TextStyle(
          fontSize: 18.0,
        ),
      ),
    ));
    children.add(SizedBox(height: 10.0));
    children.add(SizedBox(
        width: Get.width * 2 / 3, child: Image.network(info.background!)));
    children.add(SizedBox(height: 10.0));
    children.add(Container(
      child: Text(
        '视频时长：${info.duration!}',
        style: TextStyle(
          fontSize: 18.0,
        ),
      ),
    ));
    children.add(SizedBox(height: 10.0));
    children.add(Container(
      child: Text(
        info.title!,
        style: TextStyle(
          fontSize: 18.0,
        ),
      ),
    ));
    children.add(SizedBox(height: 20.0));
    for (DownloadType? typeInfo in (info.downloadTypes ?? <DownloadType>[])) {
      if (typeInfo == null) continue;
      children.add(buildTypeItem(typeInfo));
      children.add(SizedBox(height: 10.0));
    }
    return SafeArea(
      child: Material(
        child: Scaffold(
          appBar: AppBar(
            leading: GestureDetector(
              onTap: () {
                Get.back();
              },
              child: Icon(
                Icons.arrow_back,
                color: Colors.black87,
              ),
            ),
            title: Text(
              '下载页面',
              style: TextStyle(
                fontSize: 22.0,
                color: Colors.black87,
                fontWeight: FontWeight.bold,
              ),
            ),
            centerTitle: true,
            elevation: 0.0,
            backgroundColor: Colors.transparent,
          ),
          body: Container(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              children: children,
            ),
          ),
        ),
      ),
    );
  }

  Widget buildTypeItem(DownloadType typeInfo) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Expanded(
            child: Container(
              child: Center(
                  child: Text(
                typeInfo.name!,
                style: TextStyle(
                  fontSize: 18.0,
                ),
              )),
            ),
          ),
          Expanded(
            child: Container(
              child: Center(
                  child: Text(
                typeInfo.size!,
                style: TextStyle(
                  fontSize: 18.0,
                ),
              )),
            ),
          ),
          Expanded(
            child: buildDownloadBtn(typeInfo),
          ),
        ],
      ),
    );
  }

  // 动态申请权限，ios 要在info.plist 上面添加
  /// 动态申请权限，需要区分android和ios，很多时候它两配置权限时各自的名称不同
  /// 此处以保存图片需要的配置为例
  Future<bool> requestPermission() async {
    late PermissionStatus status;
    // 1、读取系统权限的弹框
    if (Platform.isIOS) {
      status = await Permission.photosAddOnly.request();
    } else {
      status = await Permission.storage.request();
    }
    // 2、假如你点not allow后，下次点击不会在出现系统权限的弹框（系统权限的弹框只会出现一次），
    // 这时候需要你自己写一个弹框，然后去打开app权限的页面
    if (status != PermissionStatus.granted) {
      showCupertinoDialog(
          context: Get.context!,
          builder: (context) {
            return CupertinoAlertDialog(
              title: const Text('You need to grant album permissions'),
              content: const Text(
                  'Please go to your mobile phone to set the permission to open the corresponding album'),
              actions: <Widget>[
                CupertinoDialogAction(
                  child: const Text('cancle'),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
                CupertinoDialogAction(
                  child: const Text('confirm'),
                  onPressed: () {
                    Navigator.pop(context);
                    // 打开手机上该app权限的页面
                    openAppSettings();
                  },
                ),
              ],
            );
          });
    } else {
      return true;
    }
    return false;
  }

  Widget buildDownloadBtn(DownloadType typeInfo) {
    return Obx(() {
      var progressMap = DyController.to.progressMapLive;
      String name = info.desc!
          .replaceAll("/", "")
          .replaceAll(" ", "")
          .replaceAll("#", "")
          .replaceAll(".", "");
      if (typeInfo.name!.toLowerCase() == "mp3" ||
          typeInfo.name!.toLowerCase() == "音频") {
        name = '$name.mp3';
      } else if (typeInfo.name!.toLowerCase() == "mp4" ||
          typeInfo.name!.toLowerCase() == "视频") {
        name = '$name.mp4';
      }

      bool isStartDownload = false;
      int progress = 0;
      progressMap.forEach((key, value) {
        if (typeInfo.url! == key && value >= 0) {
          isStartDownload = true;
          progress = value;
        }
      });

      Widget child;
      if (isStartDownload) {
        child = Center(
            child: Text(
          '$progress%',
          style: TextStyle(fontSize: 18.0, color: Colors.purple),
        ));
      } else {
        child = GestureDetector(
          onTap: () {
            requestPermission().then((grand) {
              if (grand) {
                DyController.to.progressMapLive[typeInfo.url!] = 0;
                DyController.to.progressMapLive.refresh();
                if (index == 0) {
                  DyController.to.download0(typeInfo.url!, name);
                } else if (index == 1) {
                  DyController.to.download1(typeInfo.url!, name);
                }
              }
            });
          },
          child: Container(
            color: Colors.transparent,
            child: const Center(
                child: Icon(IconData(0xe600, fontFamily: 'MIcons'))),
          ),
        );
      }
      return child;
    });
  }
}
